import java.util.LinkedList;
import java.util.Queue;

class Solution05 {
    // 定义数轴
    int[] dx = { 0, 0, -1, 1 };
    int[] dy = { 1, -1, 0, 0 };
    int n;
    // 创建一个同等规模的数组
    int[][] vis;

    public int maxDistance(int[][] grid) {
        n = grid.length;
        vis = new int[n][n];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                vis[i][j] = -1;
            }
        }
        Queue<int[]> q = new LinkedList<>();
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 1) {
                    vis[i][j] = 0;
                    // 添加到队列
                    q.add(new int[] { i, j });
                }
            }
        }
        int ret = -1;
        while (!q.isEmpty()) {
            int size = q.size();
            while (size-- != 0) {
                int[] t = q.poll();
                int a = t[0], b = t[1];
                for (int i = 0; i < 4; i++) {
                    int x = a + dx[i], y = b + dy[i];
                    // 进行判断
                    if (x >= 0 && x < n && y >= 0 && y < n && vis[x][y] == -1) {
                        vis[x][y] = vis[a][b] + 1;
                        // 添加到队列
                        q.add(new int[] { x, y });
                        ret = Math.max(ret, vis[x][y]);
                    }
                }
            }
        }
        return ret;
    }
}